package com.example.demo.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileCopyByNIO {

    public static void main(String[] args) throws Exception {
//        String path = Class.class.getClass().getResource("/").getPath();
        FileInputStream fis = new FileInputStream("E:\\IntelliJ IDEA 2017.2.5\\workplaces\\netty-demo\\src\\main\\java\\com\\example\\demo\\nio\\document\\a" +
                ".txt");
        //获取输入通道
        FileChannel fcIn = fis.getChannel();

        FileOutputStream fos = new FileOutputStream("E:\\IntelliJ IDEA " +
                "2017.2.5\\workplaces\\netty-demo\\src\\main\\java\\com\\example\\demo\\nio\\document\\b.txt");
        //获取输出通道
        FileChannel fcOut = fos.getChannel();

        //分配字节缓冲区
        ByteBuffer buf = ByteBuffer.allocate(10);

        while (true) {
            //从fcIn读到buf
            int length = fcIn.read(buf);
            System.out.println("length:" + length);
            if (length < 0) {
                break;
            }
            buf.flip();//拍板（ limit = position指针;position指针 归零）
            //从buf写入通道
            fcOut.write(buf);
            buf.clear();//position指针 归零 ；limit = capacity
        }
        fcIn.close();
        fcOut.close();


    }
}
